package com.school.service;

import com.school.common.PageRequest;
import com.school.common.PageResult;
import com.school.common.ResultCode;
import com.school.dao.DormitoryDao;
import com.school.entity.Dormitory;
import com.school.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 宿舍服务类
 */
@Slf4j
@Service
public class DormitoryService {
    
    @Autowired
    private DormitoryDao dormitoryDao;
    
    /**
     * 添加宿舍
     */
    @Transactional(rollbackFor = Exception.class)
    public Long add(Dormitory dormitory) {
        // 验证楼栋+楼层+宿舍号组合是否已存在
        Dormitory existDormitory = dormitoryDao.findByBuildingAndRoom(
                dormitory.getBuilding(), dormitory.getRoomNumber());
        if (existDormitory != null && existDormitory.getFloor().equals(dormitory.getFloor())) {
            throw new BusinessException("该楼栋的该楼层已存在此宿舍号");
        }
        
        // 验证已入住人数不能超过容纳人数
        if (dormitory.getOccupied() != null && dormitory.getCapacity() != null 
                && dormitory.getOccupied() > dormitory.getCapacity()) {
            throw new BusinessException("已入住人数不能超过容纳人数");
        }
        
        return dormitoryDao.insert(dormitory);
    }
    
    /**
     * 更新宿舍
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(Dormitory dormitory) {
        Dormitory existDormitory = dormitoryDao.findById(dormitory.getId());
        if (existDormitory == null) {
            throw new BusinessException(ResultCode.DORMITORY_NOT_EXIST);
        }
        
        // 验证已入住人数不能超过容纳人数
        if (dormitory.getOccupied() > dormitory.getCapacity()) {
            throw new BusinessException("已入住人数不能超过容纳人数");
        }
        
        dormitoryDao.update(dormitory);
    }
    
    /**
     * 删除宿舍
     */
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        Dormitory existDormitory = dormitoryDao.findById(id);
        if (existDormitory == null) {
            throw new BusinessException(ResultCode.DORMITORY_NOT_EXIST);
        }
        
        dormitoryDao.deleteById(id);
    }
    
    /**
     * 批量删除宿舍
     */
    @Transactional(rollbackFor = Exception.class)
    public int batchDelete(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new BusinessException("删除ID列表不能为空");
        }
        
        log.info("批量删除宿舍，数量: {}", ids.size());
        return dormitoryDao.batchDelete(ids);
    }
    
    /**
     * 根据ID查询宿舍
     */
    public Dormitory getById(Long id) {
        Dormitory dormitory = dormitoryDao.findById(id);
        if (dormitory == null) {
            throw new BusinessException(ResultCode.DORMITORY_NOT_EXIST);
        }
        return dormitory;
    }
    
    /**
     * 查询所有宿舍
     */
    public List<Dormitory> getAllDormitories() {
        return dormitoryDao.findAll();
    }
    
    /**
     * 分页查询宿舍列表
     */
    public PageResult<Dormitory> getPageList(String building, String roomNumber, String status, PageRequest pageRequest) {
        Map<String, Object> params = new HashMap<>();
        params.put("building", building);
        params.put("roomNumber", roomNumber);
        params.put("status", status);
        params.put("offset", pageRequest.getOffset());
        params.put("limit", pageRequest.getLimit());
        
        List<Dormitory> list = dormitoryDao.findByPage(params);
        long total = dormitoryDao.count(params);
        
        return PageResult.of(pageRequest.getPageNum(), pageRequest.getPageSize(), total, list);
    }
    
    /**
     * 批量导入宿舍
     */
    @Transactional(rollbackFor = Exception.class)
    public int batchImport(List<Dormitory> dormitories) {
        if (dormitories == null || dormitories.isEmpty()) {
            throw new BusinessException("导入数据不能为空");
        }
        
        int successCount = 0;
        for (Dormitory dormitory : dormitories) {
            // 验证必填字段
            if (dormitory.getBuilding() == null || dormitory.getBuilding().isEmpty()) {
                throw new BusinessException("楼栋不能为空");
            }
            if (dormitory.getRoomNumber() == null || dormitory.getRoomNumber().isEmpty()) {
                throw new BusinessException("宿舍号不能为空");
            }
            if (dormitory.getFloor() == null) {
                throw new BusinessException("楼层不能为空");
            }
            if (dormitory.getCapacity() == null) {
                throw new BusinessException("容纳人数不能为空");
            }
            
            // 检查楼栋+楼层+宿舍号组合是否重复
            Dormitory existDormitory = dormitoryDao.findByBuildingAndRoom(
                    dormitory.getBuilding(), dormitory.getRoomNumber());
            if (existDormitory != null && existDormitory.getFloor().equals(dormitory.getFloor())) {
                throw new BusinessException(String.format("宿舍已存在: %s栋%s层%s号", 
                        dormitory.getBuilding(), dormitory.getFloor(), dormitory.getRoomNumber()));
            }
            
            // 验证已入住人数不能超过容纳人数
            if (dormitory.getOccupied() != null && dormitory.getOccupied() > dormitory.getCapacity()) {
                throw new BusinessException("已入住人数不能超过容纳人数");
            }
            
            dormitoryDao.insert(dormitory);
            successCount++;
        }
        
        log.info("批量导入宿舍成功，数量: {}", successCount);
        return successCount;
    }
}


